  <script setup lang="ts">
import { useRoute,useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'

import api from '../api'
import TestLogo from '@/images/logo1.png'
import bg from '@/assets/images/pages/login.jpg'
import {ref,onMounted} from 'vue'
const route = useRoute()
const router = useRouter()

// 参数
const isDialogVisible = ref(false) // 用户协议弹窗
const isPasswordVisible = ref(false) // 密码可不可见
const user_id = ref('') // 用户账号--手机号
const password = ref('') // 密码
const rememberMe = ref(false) // 记住密码
const captcha_image = ref('') // 验证码图片
const captcha = ref('') // 验证码
const captcha_key = ref('') // 验证码的key
const privacyPolicies = ref(false) // 用户协议
const captcha_count_down = ref(0) // 验证码倒计时时间
const captcha_message = ref('')









// 启动倒计时函数
function startCaptchaCountdown() {
  captcha_count_down.value = 60 // 设置倒计时时间为60秒

  const countdownInterval = setInterval(() => {
    captcha_count_down.value -= 1 // 每秒减少1秒
    if (captcha_count_down.value <= 0)
      clearInterval(countdownInterval)

    // 倒计时结束，清除定时器
  }, 1000)
}

// ------------------------------ 获取验证码------------------------------
onMounted(() => {



  //get_captcha()

  if (window.screen.width <= 1366) {
    document.body.style.zoom = '75%'

    // eslint-disable-next-line @typescript-eslint/no-shadow
    const login = document.getElementById('login-container')

    // login.style.height = `${100 / 0.75}vh`
    if (login) {
      login.style.height = `${80}vh`
    }
  }
})

function get_captcha() {
  api.login
    .get_captcha()
    .then(data => {
      captcha_image.value = data.image
      captcha_key.value = data.id
      startCaptchaCountdown() // 启动倒计时
      captcha_message.value = '验证码已刷新，请注意时间！' // 显示提示消息
      setTimeout(() => {
        captcha_message.value = '' // 5秒后清除提示消息
      }, 5000)
    })
    .catch(error => {
      console.log('获取验证码失败：', error)
    })
}

// ------------------------------ 登陆-----------------------------
function login() {
  if (user_id.value === '') {
    ElMessage.error('账号为空！')
  }
  else if (password.value === '') {
    ElMessage.error('密码为空！')
  }
  else if (captcha.value === '') {
    ElMessage.error('验证码为空！')
  }
  else if (!privacyPolicies.value) {
    ElMessage.error('用户协议与隐私政策未同意！')
  }
  else {
    api.login
      .login(
        user_id.value,
        password.value,
        captcha_key.value,
        captcha.value,
      )
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('登录成功！')

          const user_detail = res.data.data

          localStorage.setItem('userData', JSON.stringify(user_detail))
          localStorage.setItem('accessToken', user_detail.token)
          localStorage.setItem('token_expired_at', user_detail.token_expired_at)
          axios.defaults.headers.common.Authorization = user_detail.token

          router.replace(route.query.to ? String(route.query.to) : '/')
        }
        else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(error => {
        console.log('登陆失败：', error)
      })
  }
}

// 跳转到注册
function register() {
  router.replace(route.query.to ? String(route.query.to) : '/register')
}

// // 用户协议
// function readFile(filePath: any) {
//   let xhr = null
//   const okStatus = document.location.protocol === 'file' ? 0 : 200

//   xhr = window.XMLHttpRequest
//     ? new XMLHttpRequest()
//     : new ActiveXObject('Microsoft.XMLHTTP')
//   xhr.open('GET', filePath, false)
//   xhr.overrideMimeType('text/html;charset=utf-8')
//   xhr.send(null)

//   return xhr.status === okStatus ? xhr.responseText : null
// }

// const privated = ref('')

// function privacy() {
//   const filePath = '/privacy.html'

//   privated.value = readFile(filePath)
//   isDialogVisible.value = true
// }

// ... existing code ...
// 用户协议
function readFile(filePath: any) {
  return new Promise((resolve, reject) => {
    let xhr: XMLHttpRequest | null = null;
    
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    } else {
      // 兼容旧版IE
      // @ts-ignore ActiveXObject 仅用于 IE 兼容
      xhr = new (window as any).ActiveXObject("Microsoft.XMLHTTP");
    }
    
    if (!xhr) {
      reject(new Error('无法创建XMLHttpRequest对象'));
      return;
    }
    
    xhr.open('GET', filePath, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(xhr.responseText);
        } else {
          reject(new Error(`加载失败，状态码: ${xhr.status}`));
        }
      }
    };
    xhr.onerror = function() {
      reject(new Error('网络错误'));
    };
    xhr.send(null);
  });
}

const privated = ref('')

function privacy() {
  const filePath = '/mars-1/privacy.html'
  
  readFile(filePath)
    .then((data: any) => {
      privated.value = data
      isDialogVisible.value = true
    })
    .catch((error: any) => {
      ElMessage.error('用户协议加载失败: ' + error.message)
      console.error('用户协议加载失败:', error)
    })
}
// ... existing code ...

</script>

<template>
  <div id="login-container">
    <el-dialog
      v-model="isDialogVisible"
      fullscreen
      title="《数据平台隐私条款》"
      class="mars-dialog"
    >
      <div class="agreement">
        <p v-html="privated" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 顶部导航 -->
    <!-- <div class="mars-header">
      <router-link to="/">
        <div class="logo-container">
          <img
            :src="TestLogo"
            alt="Logo"
            class="mars-logo"
          >
        </div>
      </router-link>
    </div> -->

    <!-- 主内容区域 -->
    <div class="mars-container">
      <div class="mars-form-wrapper">
        <!-- 欢迎信息 -->
        <div class="welcome-section">
          <h2 class="mars-title">欢迎来到数据服务平台！</h2>
          <p class="mars-subtitle">请先登录账号!</p>
        </div>

        <!-- 登录表单 -->
        <el-form @submit.prevent="login" class="mars-form">
          <!-- 用户名 -->
          <el-form-item>
            <el-input
              v-model="user_id"
              placeholder="请输入用户名"
              size="large"
              class="mars-input"
            >
              <template #prefix>
                <el-icon class="mars-icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item>
            <el-input
              v-model="password"
              placeholder="密码"
              :type="isPasswordVisible ? 'text' : 'password'"
              size="large"
              class="mars-input"
            >
              <template #prefix>
                <el-icon class="mars-icon"><Lock /></el-icon>
              </template>
              <template #suffix>
                <el-icon 
                  class="password-toggle"
                  @click="isPasswordVisible = !isPasswordVisible"
                >
                  <View v-if="isPasswordVisible" />
                  <Hide v-else />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item>
            <div class="captcha-container">
              <el-input
                v-model="captcha"
                placeholder="请输入验证码"
                size="large"
                class="mars-input captcha-input"
              />
              <div class="captcha-right">
                <img
                  :src="captcha_image"
                  alt="验证码"
                  class="captcha-image"
                  @click="get_captcha"
                />
                <div class="captcha-refresh" @click="get_captcha">
                  <span v-if="captcha_count_down === 0" class="refresh-text">刷新</span>
                  <span v-else class="countdown">{{ captcha_count_down }}秒</span>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 验证码消息 -->
          <div v-if="captcha_message !== ''" class="captcha-message">
            {{ captcha_message }}
          </div>

          <!-- 选项区域 -->
          <div class="options-section">
            <div class="remember-register">
              <el-checkbox v-model="rememberMe" class="mars-checkbox">
                <span class="checkbox-label">记住密码</span>
              </el-checkbox>
              <el-button type="primary" link @click="register" class="mars-link">
                注册
              </el-button>
            </div>

            <div class="privacy-agreement">
              <el-checkbox v-model="privacyPolicies" class="mars-checkbox">
                <span class="privacy-label">
                  我已阅读并同意
                  <el-button type="primary" link @click="privacy" class="mars-link">
                    用户协议和隐私政策
                  </el-button>
                </span>
              </el-checkbox>
            </div>
          </div>

          <!-- 登录按钮 -->
          <el-button
            type="primary"
            size="large"
            class="mars-login-btn"
            @click="login"
          >
            登录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
#login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-image: url('@/assets/images/pages/login.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  position: relative;
  overflow: hidden;
}

/* 强烈淡化的背景遮罩 */
#login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    linear-gradient(135deg, 
      rgba(0, 10, 20, 0.1) 0%, 
      rgba(0, 0, 0, 0.2) 50%,
      rgba(10, 0, 20, 0.1) 100%);
  z-index: 1;
}

/* 顶部导航 - 强烈淡化边框 */
.mars-header {
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(15px);
  padding: 15px 40px;
  flex-shrink: 0;
  border-bottom: 1px solid rgba(188, 78, 51, 0.1); /* 强烈淡化边框 */
  position: relative;
  z-index: 2;
  
  .logo-container {
    display: flex;
    justify-content: flex-start;
  }
  
  .mars-logo {
    height: 60px;
    width: 200px;
    filter: brightness(0) invert(1);
  }
}

/* 主容器 */
.mars-container {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 40px;
  position: relative;
  z-index: 2;
}

/* 火星科技表单 - 强烈淡化边框 */
.mars-form-wrapper {
  width: 400px;
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  padding: 40px;
  border: 1px solid rgba(255, 255, 255, 0.05); /* 强烈淡化边框 */
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.05);
  position: relative;
}

/* 移除发光边框效果 */

.welcome-section {
  text-align: center;
  margin-bottom: 32px;
  
  .mars-title {
    color: #fff;
    margin-bottom: 12px;
    font-size: 1.5rem;
    font-weight: 600;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
  }
  
  .mars-subtitle {
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
    font-size: 1rem;
  }
}

/* 火星科技输入框 - 强烈淡化边框 */
:deep(.mars-input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.08) !important;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1) !important; /* 强烈淡化边框 */
    border-radius: 10px !important;
    box-shadow: 
      inset 0 1px 3px rgba(0, 0, 0, 0.1),
      0 2px 8px rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease;
    
    &.is-focus {
      border-color: rgba(188, 78, 51, 0.3) !important; /* 强烈淡化聚焦边框 */
      box-shadow: 
        inset 0 1px 3px rgba(0, 0, 0, 0.1),
        0 2px 12px rgba(188, 78, 51, 0.1) !important;
    }
  }
  
  .el-input__inner {
    color: #fff !important;
    background: transparent !important;
    font-weight: 500;
    
    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }
  
  .mars-icon {
    color: rgba(188, 78, 51, 0.6) !important;
  }
}

/* 密码切换图标 */
.password-toggle {
  cursor: pointer;
  transition: color 0.3s;
  color: rgba(188, 78, 51, 0.6) !important;
  
  &:hover {
    color: rgba(188, 78, 51, 0.8) !important;
  }
}

/* 火星风格复选框 - 淡化边框 */
:deep(.mars-checkbox) {
  .el-checkbox__input {
    .el-checkbox__inner {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2); /* 淡化边框 */
      border-radius: 4px;
      
      &::after {
        border-color: rgba(188, 78, 51, 0.8);
      }
    }
    
    &.is-checked .el-checkbox__inner {
      background: rgba(188, 78, 51, 0.15);
      border-color: rgba(188, 78, 51, 0.4); /* 淡化边框 */
    }
  }
  
  .el-checkbox__label {
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 500;
  }
}

.checkbox-label {
  color: rgba(255, 255, 255, 0.9);
}

/* 验证码区域 */
.captcha-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  
  .captcha-input {
    flex: 1;
  }
  
  .captcha-right {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    min-width: 100px;
    
    .captcha-image {
      height: 45px;
      border-radius: 6px;
      border: 1px solid rgba(255, 255, 255, 0.1); /* 淡化边框 */
      cursor: pointer;
      background: rgba(255, 255, 255, 0.05);
      backdrop-filter: blur(5px);
    }
    
    .captcha-refresh {
      .refresh-text {
        font-size: 0.8rem;
        color: rgba(188, 78, 51, 0.7);
        cursor: pointer;
        font-weight: 500;
        transition: color 0.3s;
        
        &:hover {
          color: rgba(188, 78, 51, 0.9);
        }
      }
      
      .countdown {
        font-size: 0.8rem;
        color: rgba(255, 255, 255, 0.5);
        font-weight: 500;
      }
    }
  }
}

.captcha-message {
  color: rgba(255, 107, 107, 0.8);
  font-size: 0.8rem;
  text-align: center;
  margin-bottom: 16px;
}

/* 选项区域 */
.options-section {
  margin-bottom: 24px;
  
  .remember-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .privacy-agreement {
    padding: 16px;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(5px);
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.05); /* 强烈淡化边框 */
    
    .privacy-label {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 0.9rem;
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

/* 火星风格链接 */
:deep(.mars-link) {
  color: rgba(188, 78, 51, 0.7) !important;
  font-weight: 500;
  
  &:hover {
    color: rgba(188, 78, 51, 0.9) !important;
  }
}

/* 火星登录按钮 - 淡化边框 */
.mars-login-btn {
  width: 100%;
  height: 48px;
  font-size: 1rem;
  font-weight: 600;
  border-radius: 10px;
  background: linear-gradient(135deg, rgba(188, 78, 51, 0.7) 0%, rgba(139, 69, 19, 0.8) 100%);
  border: 1px solid rgba(188, 78, 51, 0.2); /* 淡化边框 */
  box-shadow: 
    0 4px 15px rgba(188, 78, 51, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    background: linear-gradient(135deg, rgba(188, 78, 51, 0.8) 0%, rgba(139, 69, 19, 0.9) 100%);
    box-shadow: 
      0 6px 20px rgba(188, 78, 51, 0.3),
      inset 0 1px 0 rgba(255, 255, 255, 0.1);
    transform: translateY(-2px);
  }
  
  &:active {
    transform: translateY(0);
  }
}

/* 火星风格弹窗 - 淡化边框 */
:deep(.mars-dialog) {
  .el-dialog {
    background: rgba(20, 20, 20, 0.95);
    backdrop-filter: blur(25px);
    border-radius: 16px;
    border: 1px solid rgba(255, 255, 255, 0.05); /* 强烈淡化边框 */
    
    .el-dialog__header {
      border-bottom: 1px solid rgba(255, 255, 255, 0.05); /* 强烈淡化边框 */
      margin-right: 0;
    }
    
    .el-dialog__title {
      color: #fff;
    }
    
    .agreement {
      max-height: 60vh;
      overflow-y: auto;
      line-height: 1.6;
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mars-container {
    padding: 20px;
    justify-content: center;
  }
  
  .mars-form-wrapper {
    width: 100%;
    max-width: 400px;
    padding: 30px 24px;
  }
  
  .mars-header {
    padding: 15px 20px;
  }
  
  .captcha-container {
    flex-direction: column;
    
    .captcha-right {
      flex-direction: row;
      justify-content: space-between;
      width: 100%;
    }
  }
}
</style>